package com.emm.yixun.website.controller.customer;

//框架包
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.emm.yixun.common.model.dto.*;
import com.emm.yixun.common.model.enums.*;
import com.emm.yixun.marketing.service.NeedReceiveRefundServiceFacade;
import com.emm.yixun.website.common.utils.BeanUtil;
import org.activiti.engine.IdentityService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.anotations.UserOperateLog;
import com.emm.yixun.common.enums.FunctionTypeEnum;
import com.emm.yixun.common.enums.ModelTypeEnum;
import com.emm.yixun.common.enums.ProcessTypeEnums;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.BusinessAbnorma;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.HaveReceiveRefund;
import com.emm.yixun.common.model.PayDeposit;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.customer.service.PayDepositServiceFacade;
import com.emm.yixun.customer.service.SignedServiceFacade;
import com.emm.yixun.estate.service.ProjectRoomServiceFacade;
import com.emm.yixun.marketing.service.BusinessAbnormaServiceFacade;
import com.emm.yixun.marketing.service.HaveReceiveRefundServiceFacade;
import com.emm.yixun.system.service.BaseCodeValueServiceFacade;
import com.emm.yixun.system.service.BusinessLogServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.DateUtils;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.service.ActivitiProcessServiceImpl;
import com.emm.yixun.website.service.image.WsImageService;
import com.emm.yixun.website.service.payDeposit.PayDepositService;
import com.emm.yixun.website.vo.common.ExtResultVo;
//common
//website
//变化的引用

@Controller
@RequestMapping("/customer/payDeposit/")
public class PayDepositController extends BaseController<PayDeposit> {

	@Autowired
	private PayDepositServiceFacade payDepositServiceFacade;
	@Autowired
	private PayDepositService payDepositService;
	@Autowired
	private ProjectRoomServiceFacade projectRoomServiceFacade;
	@Autowired
	private CustomerServiceFacade customerServiceFacade;
	@Autowired
	private UserServiceFacade userServiceFacade;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private BusinessAbnormaServiceFacade businessAbnormaServiceFacade;
	@Autowired
	private HaveReceiveRefundServiceFacade haveReceiveRefundServiceFacade;
	@Autowired
	private SignedServiceFacade signedServiceFacade;
	@Autowired
	private ActivitiProcessServiceImpl activitiProcessService;
	@Autowired
	private BaseCodeValueServiceFacade baseCodeValueServiceFacade;
	@Autowired
	private WsImageService wsImageService;
	@Autowired
	private BusinessLogServiceFacade businessLogServiceFacade;

    @Autowired
    private NeedReceiveRefundServiceFacade needReceiveRefundServiceFacade;

	@RequestMapping(value = "index")
	public String index(ModelMap map) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) {
			// 查询菜单按钮权限
			map.put("permitBtn", getPermissionBtnArray());
			return "/customer/payDeposit/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}

	@RequestMapping(value = "toChangeName")
	public String toChangeName(String payDepositId, ModelMap map) {
		map.put("payDepositId", payDepositId);
		if (StringUtils.isNotBlank(payDepositId)) {
			Response<PayDeposit> response = payDepositServiceFacade.findById(Long.valueOf(payDepositId));
			if (response.isSuccess() && response.getEntity() != null) {
				map.put("projectId", response.getEntity().getProjectId());
			}
		}
		User user = ShiroUtil.getCurrentUser();
		String typeName = BaseCodeTypeEnum.getByNo(BaseCodeTypeEnum.TYPE_TWELVE.getNo()).getDes();
		BaseCodeValueDto bcvDto = new BaseCodeValueDto();
		bcvDto.setMerchantId(user.getMerchantId());
		bcvDto.setTypeName(typeName);
		bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		// *1解决数字排序问题.例如 1,2,10.排序后会显示成 1,10,2
		bcvDto.setOrders("t.sort*1");
		JSONArray dtArray = JSONArray.parseArray(baseCodeValueServiceFacade.getBcvJsonArray(bcvDto));
		map.put("documentType", dtArray.toJSONString());
		return "/customer/payDeposit/changeName";
	}

	@RequestMapping(value = "toAdd")
	public String toAdd(ModelMap map, String roomId, String customerId, HttpServletRequest request, String returnUrl,
			String isChooseCustomer) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:payDeposit:add")) {
			Boolean showChooseCustomer = Boolean.FALSE;
			map.put("permitBtn", getPermissionBtnArray());
			User user = ShiroUtil.getCurrentUser();
			map.put("customerId", StringUtils.isBlank(customerId) ? "" : customerId);
			Long projectId = null;
			if (StringUtils.isNotBlank(customerId)) {
				Response<Customer> customerResponse = customerServiceFacade.findById(Long.valueOf(customerId));
				if (customerResponse.isSuccess() && null != customerResponse.getEntity()) {
					map.put("customerProjectId", customerResponse.getEntity().getProjectId());
					projectId = customerResponse.getEntity().getProjectId();
				}
			}
			//当projectId为null时，从房间表获取projectId
			if(projectId == null){
				Response<ProjectRoom> rooms = projectRoomServiceFacade.findById(Long.parseLong(roomId));
				if(rooms.isSuccess() && null != rooms.getEntity()){
					projectId = rooms.getEntity().getProjectId();
				}
			}
			
			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setMerchantId(user.getMerchantId());
			bcvDto.setProjectId(projectId);
			bcvDto.setTypeValue("documentType");
			bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			// *1解决数字排序问题.例如 1,2,10.排序后会显示成 1,10,2
			bcvDto.setOrders("t.sort*1");
			JSONArray dtArray = JSONArray.parseArray(baseCodeValueServiceFacade.getBcvJsonArray(bcvDto));
			map.put("documentType", dtArray.toJSONString());

			map.put("roomId", StringUtils.isBlank(roomId) ? "" : roomId);
			map.put("menu", request.getParameter("menu"));
			if (!com.alibaba.druid.util.StringUtils.isEmpty(returnUrl)) {
				map.put("returnUrl", returnUrl.replace(",", "/").replace("(", "?").replace(")", "="));
			}
			if (StringUtils.isNotBlank(isChooseCustomer))
				showChooseCustomer = Boolean.TRUE;
			map.put("showChooseCustomer", showChooseCustomer);
			return "/customer/payDeposit/add";
		} else {
			return Const.NO_AUTHORIZED_URL;
		}

		/*
		 * if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) { } return Const.NO_AUTHORIZED_URL;
		 */
	}

	@RequestMapping(value = "payDepositChangeName", method = RequestMethod.POST)
	public @ResponseBody
	AjaxRes payDepositChangeName(String params) {
		AjaxRes ar = getAjaxRes();
		User user = ShiroUtil.getCurrentUser();
		try {
			Response<Boolean> response = payDepositServiceFacade.changeService(params, ShiroUtil.getCurrentUser());
			if (response.isSuccess()) {
				ar.setRes(Const.SUCCEED);
				ar.setResMsg("更名成功!");
			} else {
				ar.setResMsg(response.getResultMessage());
			}
		}catch(Exception ex) {
			//新增业务操作异常记录
			businessLogServiceFacade.saveExceptionLog(user, "认筹更名", params, JSONObject.toJSONString(ex));
			logger.error("新增认筹错误", ex);
			ar.setResMsg("更名错误，请联系管理员！");
		}
		
		return ar;
	}

	// 新增返回实体对象
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	@UserOperateLog(functionName = FunctionTypeEnum.FUNCTIONTYPE_3, modelName = ModelTypeEnum.MODELTYPE_2, roomKey = "roomId")
	public AjaxRes add(String params, String processKey) {
		AjaxRes ar = getAjaxRes();

		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		User user = ShiroUtil.getCurrentUser();
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:payDeposit:add"))) {
			try {
				//原始入参,在进行操作前记录下来.供上传附件时使用.
				PayDepositDto originPayDepositDto = JSONObject.parseObject(params, PayDepositDto.class);
				Response<PayDepositDto> response = payDepositServiceFacade.addPayDeposit(params, user);
				String resMsg = "认筹成功";
				if (response.isSuccess()) {
					if (StringUtils.isNotBlank(processKey)) {
						PayDepositDto payDepositDto = response.getEntity();
						Long projectId = payDepositDto.getProjectId();
						if (null == projectId) {
							ar.setFailMsg("项目不存在!");
							return ar;
						}
						/*// 动态获取价格方案流程KEY
						String startProcessKey = activitiProcessService.getProcessKey(user.getMerchantId(), projectId,
								ProcessTypeEnums.PROCESS_KEY_3);
						if (StringUtils.isEmpty(startProcessKey)) {
							ar.setFailMsg("项目未设置认筹审批流程,请去项目流程菜单配置！");
							return ar;
						}
						processKey = startProcessKey;
						boolean isSeting = activitiProcessService.checkNodeUser(user.getMerchantId(), projectId,
								processKey);
						if (!isSeting) {
							ar.setFailMsg("认筹审批流程节点人员未设置");
							return ar;
						}
						*//**
						 * 1.提交认筹审核,修改状态为审核中,保存流程ID 2.修改房源状态认筹
						 *//*
						// 判断是否为无房认筹 如果是则取客户对应的项目负责人
						identityService.setAuthenticatedUserId(user.getUserAccount());
						String pid = activitiProcessService.startProcessInstance(user.getMerchantId(), projectId,
								processKey, payDepositDto.getId().toString(), null);*/
						PayDepositDto updateDto = new PayDepositDto();
						updateDto.setId(payDepositDto.getId());
						updateDto.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
//						updateDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
//						updateDto.setProcInstId(pid);
						updateDto.setProcInstId("sys_auto");
						updateDto.setCheckDate(new Date());
						payDepositServiceFacade.updateByPrimaryKey(updateDto, true);
						PayDepositDto dto = JSONObject.parseObject(params, PayDepositDto.class);
						if (dto.getIsPaydeposit().equals(IsPaydepositEnum.NO.getNo())) {
							// 修改房源状态为认筹
							ProjectRoomDto projectRoomDto = new ProjectRoomDto();
							projectRoomDto.setId(payDepositDto.getRoomId());
							projectRoomDto.setRoomStatus(RoomStatusEnum.RESERVE.getNo());
							projectRoomServiceFacade.updateByPrimaryKey(projectRoomDto, true);
						}

						// 创建并发送提醒消息
//						if (pid != null) {
//							payDepositDto.setProcInstId(pid);
//						}
						payDepositDto.setProcInstId("sys_auto");
						//添加流程审核需要的图片
						// 保存认筹主表信息
						
						wsImageService.uploadAttachment(originPayDepositDto.getFileArr(), String.valueOf(payDepositDto.getId()), originPayDepositDto.getImageType(), payDepositDto.getProjectCode());
						/*
						 * CommonResDTO resDto = payDepositServiceFacade.addNotice_RC(payDepositDto, variables, pid); if
						 * ("1".equals(resDto.getResult())) { logger.error("创建并发送消息: ", "消息创建并发送成功!"); }
						 */

					}else{
						wsImageService.uploadAttachment(originPayDepositDto.getFileArr(), String.valueOf(response.getEntity().getId()), originPayDepositDto.getImageType(), response.getEntity().getProjectCode());
						resMsg = "认筹保存成功";
					}
                    PayDepositDto payDepositDto = response.getEntity();
                    /**
                     * 1.修改认筹记录审核状态为通过
                     * 2.记录房源变更记录
                     * 3.记录应收记录
                     * 4.更改客户交易状态为认筹，判断是否多套交易并更新状态
                     */
                    //1.修改认筹记录审核状态为通过
                    PayDepositDto updateTmp = new PayDepositDto();
                    updateTmp.setId(payDepositDto.getId());
                    updateTmp.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
                    updateTmp.setCheckDate(new Date());
                    payDepositServiceFacade.updateByPrimaryKey(updateTmp, true);

                    //2.记录房源变更记录
                        /*if(payDepositDto.getRoomId() != null){
                            RoomChangeHistoryDto rdto=new RoomChangeHistoryDto();
                            rdto.setRoomId(payDeposit.getRoomId());
                            rdto.setBusinessDynamics("认筹");
                            rdto.setRemark("房源由【可售】转为【认筹】");
                            rdto.setMerchantId(payDeposit.getMerchantId());
                            rdto.setAccessCode(payDeposit.getAccessCode());
                            rdto.setCreateUserId(payDeposit.getCreateUserId());
                            rdto.setUserCode(payDeposit.getUserCode());
                            rdto.setDelFlag("0");
                            rdto.setBusinessHref("/customer/payDeposit/toView?id="+payDeposit.getId()+"&returnUrl=,marketing,room,index");
                            rdto.setUpdateUserId(payDeposit.getUpdateUserId());
                            rdto.setUpdateTime(new Date());
                            Response<RoomChangeHistoryDto> rchSaveResponse=getRoomChangeHistoryServiceFacade().save(rdto);
                            if(!rchSaveResponse.isSuccess()){
                                throw new Exception(rchSaveResponse.getResultMessage());
                            }
                        }*/

                    //3.记录应收记录
                    NeedReceiveRefundDto needReceiveRefundDto=new NeedReceiveRefundDto();
                    needReceiveRefundDto.setRelationId(payDepositDto.getId());
                    needReceiveRefundDto.setBusinessType("0");
                    needReceiveRefundDto.setTotalReceivablesAmount(payDepositDto.getPayDepositAmount());
                    needReceiveRefundDto.setCustomerId(payDepositDto.getCustomerId());
                    needReceiveRefundDto.setRoomId(payDepositDto.getRoomId());
                    needReceiveRefundDto.setStatus("1");
                    needReceiveRefundDto.setPostponedStatus("0");
                    needReceiveRefundDto.setDocType("0");
                    needReceiveRefundDto.setRemark("认筹收款");
                    needReceiveRefundDto.setHousingFundType(HousingFundTypeEnum.FUNDTYPE_1.getNo());
                    needReceiveRefundDto.setBusinessFlag(BusinessFlagEnum.BUSINESSFLAG_1.getNo());
                    needReceiveRefundDto.setPostponedStatus("0");

                    needReceiveRefundDto.setMerchantId(payDepositDto.getMerchantId());
                    needReceiveRefundDto.setUserCode(payDepositDto.getUserCode());
                    needReceiveRefundDto.setAccessCode(payDepositDto.getAccessCode());
                    needReceiveRefundDto.setCreateUserId(payDepositDto.getCreateUserId());
                    needReceiveRefundDto.setDelFlag("0");
                    needReceiveRefundDto.setUpdateUserId(payDepositDto.getUpdateUserId());
                    needReceiveRefundDto.setUpdateTime(new Date());
                    Response<NeedReceiveRefundDto> nrrdSaveResponse=needReceiveRefundServiceFacade.save(needReceiveRefundDto);
                    if(!nrrdSaveResponse.isSuccess()){
                        throw new Exception(nrrdSaveResponse.getResultMessage());
                    }
                    /**
                     * 4.更改客户交易状态为认筹，判断是否多套交易并更新状态 todo
                     * @param bugType 业务类型： 1 认筹、2 认购、3 签约
                     * @param busId 对应业务类型Id
                     * @param customerId 客户Id
                     * @param userId 用户Id
                     */
                    payDepositServiceFacade.getCustomerEntity("1", payDepositDto.getId(),payDepositDto.getCustomerId() , payDepositDto.getUpdateUserId());


                    /**
                     * （认筹审核通过）推送消息到app
                     * @author ny
                     * @param param noticeType 提醒类型, noticeBusinessId 业务主键Id
                     * @return 【${auditStatus}】房号：${roomName}；客户：${customer};
                     */
                    /*NoticeEntity noticeEntity = new NoticeEntity();
                    noticeEntity.setNoticeBusinessId(payDeposit.getId());
                    noticeEntity.setNoticeType("1");
                    noticeEntity.setProcessInstanceId(processInstanceId);
                    getPayDepositNoticeFacade().createPayDepositNotice(noticeEntity);
                    *//**
                     * 调用渠道接口
                     * @author Administrator
                     * 交易状态  1=认筹
                     *//*
                    getChannelSendHttpMessageService().sendTransaction(payDeposit.getId(), TransTypeEnum.PAYDEPOSIT.getNo(), false);*/

					ar.setObj(response.getEntity().getId());
					ar.setRes(Const.SUCCEED);
					ar.setResMsg(resMsg);
				} else {
					ar.setFailMsg(response.getResultMessage());
				}
			} catch (Exception ex) {
				//新增业务操作异常记录
				businessLogServiceFacade.saveExceptionLog(user, "新增认筹", params, JSONObject.toJSONString(ex));
				
				logger.error(ex.toString(), ex);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}

	@RequestMapping(value = "toView")
	public String toView(ModelMap map, Long id, String processFlag, HttpServletRequest request, String returnUrl) {
		/* if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) { */
		map.put("processFlag", processFlag != null ? processFlag : "false");
		User user = ShiroUtil.getCurrentUser();
		String typeName = BaseCodeTypeEnum.getByNo(BaseCodeTypeEnum.TYPE_TWELVE.getNo()).getDes();
		BaseCodeValueDto bcvDto = new BaseCodeValueDto();
		bcvDto.setMerchantId(user.getMerchantId());
		bcvDto.setTypeName(typeName);
		bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		// *1解决数字排序问题.例如 1,2,10.排序后会显示成 1,10,2
		bcvDto.setOrders("t.sort*1");
		JSONArray dtArray = JSONArray.parseArray(baseCodeValueServiceFacade.getBcvJsonArray(bcvDto));
		map.put("documentType", dtArray.toJSONString());
		// 查询菜单按钮权限
		map.put("permitBtn", getPermissionBtnArray());
		map.put("payDepositeId", id);
		map.put("estateRecord", "{paydepositName:'否'}");
		map.put("customerRecord", "{}");
		map.put("payDepositeRecord", "{}");
		map.put("isPaydeposit", "1");
		map.put("menu", request.getParameter("menu"));
		Response<PayDeposit> response = payDepositServiceFacade.findById(id);
		if (response.isSuccess()) {

			HashMap<String, Double> maps = signedServiceFacade.signedContractAmount(id, null);

			// 认筹信息
			PayDeposit payDeposit = response.getEntity();
			map.put("procInstId", payDeposit.getProcInstId());
			HaveReceiveRefundDto haveReceiveRefundDto = new HaveReceiveRefundDto();
			haveReceiveRefundDto.setReceivablesType("0");// 认筹
			haveReceiveRefundDto.setRelationId(payDeposit.getId());
			// needReceiveRefundDto.setStatus("0");// 已结清
			ResponseList<HaveReceiveRefund> response3 = haveReceiveRefundServiceFacade.findByDto(haveReceiveRefundDto);
			if (response3.isSuccess()) {
				List<HaveReceiveRefund> haveReceiveRefunds = response3.getEntity();
				if (haveReceiveRefunds != null && haveReceiveRefunds.size() != 0) {
					BigDecimal total = new BigDecimal("0.00");
					for (HaveReceiveRefund refund : haveReceiveRefunds) {
						if (!refund.getBusinessFlag().equals(BusinessFlagEnum.BUSINESSFLAG_11.getNo())) {
							map.put("amountDetail", "1");
							total = total.add(refund.getRealAmount());
						}
					}
					if (total.compareTo(payDeposit.getPayDepositAmount()) == 0) {
						map.put("shouStatus", "1");
					} else {
						map.put("shouStatus", "0");
					}
				} else {
					map.put("shouStatus", "0");
				}
			} else {
				map.put("shouStatus", "0");
			}
			map.put("auditStatus", payDeposit.getAuditStatus());
			map.put("businessStatus", payDeposit.getBusinessStatus());
			Response<ProjectRoom> response2 = projectRoomServiceFacade.findById(payDeposit.getRoomId());
			if (response2.isSuccess()) {
				ProjectRoom projectRoom = response2.getEntity();
				map.put("roomStatus", projectRoom.getRoomStatus());
			} else {
				map.put("roomStatus", "-1");
			}
			String payDepositeRecord = JSON.toJSONString(payDeposit);
			JSONObject object = JSONObject.parseObject(payDepositeRecord);
			Double payAepositAmount = maps.get("payAepositAmount");
			object.put("payAepositAmount", payAepositAmount);

			payDepositeRecord = JSON.toJSONString(object);

			map.put("payDepositeRecord", payDepositeRecord);
			map.put("isPaydeposit", payDeposit.getIsPaydeposit());
			// 房源信息
			String paydepositName = null;
			if (payDeposit.getIsPaydeposit().equals("0")) {
				paydepositName = "否";
			} else {
				paydepositName = "是";
			}

			if (payDeposit.getIsPaydeposit().equals("0")) {
				JSONObject estateRecord = getEstateRecord(payDeposit.getRoomId());
				estateRecord.put("paydepositName", paydepositName);
				estateRecord.put("isPaydeposit", payDeposit.getIsPaydeposit());
				estateRecord.put("calculateArea", payDeposit.getCalculateArea());
				estateRecord.put("unitPrice", payDeposit.getDiscountPrice());
				estateRecord.put("totalPrice", payDeposit.getDiscountTotalPrice());
				map.put("estateRecord", estateRecord.toJSONString());
			} else {
				JSONObject estateRecord = new JSONObject();
				estateRecord.put("paydepositName", paydepositName);
				map.put("estateRecord", estateRecord.toJSONString());
			}
			user = userServiceFacade.findById(payDeposit.getAgentId()).getEntity();
			map.put("userName", user.getUserName());
			JSONObject customerRecord = getCustomerRecord(payDeposit.getCustomerId());
			map.put("customerRecord", customerRecord.toJSONString());

			BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
			businessAbnormaDto.setBusinessId(payDeposit.getId());
			businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_7.getNo());
			businessAbnormaDto.setOrders(" t.create_time DESC");
			ResponseList<BusinessAbnorma> businessAbnormaResponse = businessAbnormaServiceFacade
					.findByDto(businessAbnormaDto);
			String businessAbnormaId = "";
			if (businessAbnormaResponse.isSuccess() && null != businessAbnormaResponse.getEntity()
					&& businessAbnormaResponse.getEntity().size() > 0) {
				businessAbnormaId = String.valueOf(businessAbnormaResponse.getEntity().get(0).getId());
			}
			map.put("businessAbnormaId", businessAbnormaId);
		}
		if (!com.alibaba.druid.util.StringUtils.isEmpty(returnUrl)) {
			map.put("returnUrl", returnUrl.replace(",", "/").replace("(", "?").replace(")", "="));
			map.put("returnBackParam", returnUrl);
		}

		return "/customer/payDeposit/view";
		/*
		 * } return Const.NO_AUTHORIZED_URL;
		 */
	}

	// 组装房源信息
	public JSONObject getEstateRecord(Long roomId) {
		JSONObject projectRoomJson = new JSONObject();
		Response<ProjectRoom> response = projectRoomServiceFacade.findById(roomId);
		if (response.isSuccess()) {
			ProjectRoom projectRoom = response.getEntity();
			projectRoomJson.put("combinedName", projectRoom.getCombinedName());
			projectRoomJson.put("buildingArea", projectRoom.getBuildingArea());
			projectRoomJson.put("sharingArea", projectRoom.getSharingArea());
			projectRoomJson.put("innerArea", projectRoom.getInnerArea());
			projectRoomJson.put("billingArea", projectRoom.getBillingArea());
			projectRoomJson.put("roomStatusName", StringUtils.isNotBlank(projectRoom.getRoomStatus()) ? RoomStatusEnum
					.getByNo(projectRoom.getRoomStatus()).getDes() : "");
		}
		return projectRoomJson;
	}

	// 组装客户信息
	public JSONObject getCustomerRecord(Long customerId) {
		JSONObject customerJson = new JSONObject();
		Response<Customer> response = customerServiceFacade.findById(customerId);
		if (response.isSuccess()) {
			Customer customer = response.getEntity();
			customerJson.put("customerName", customer.getCustomerName());

			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setMerchantId(customer.getMerchantId());
			ResponseList<BaseCodeValue> bcvResList = baseCodeValueServiceFacade.selectListFilterDelFlag(bcvDto);
			Map<Long, String> bcvMap = new HashMap<Long, String>();
			if (bcvResList.isSuccess()) {
				List<BaseCodeValue> bcvList = bcvResList.getEntity();
				for (BaseCodeValue bcv : bcvList) {
					bcvMap.put(bcv.getId(), bcv.getCodeName());
				}
			}
			if (null != customer.getPeDocumentType()) {
				customerJson.put("peDocumentTypeName", bcvMap.get(Long.parseLong(customer.getPeDocumentType())));
			}

			customerJson.put("peDocumentNumber", customer.getPeDocumentNumber());
			customerJson.put("customerPhone", customer.getCustomerPhone());
			customerJson.put("peContactAddress", customer.getPeContactAddress());
			customerJson.put("pePostcode", customer.getPePostcode());
			if (null != customer.getCustomerOrigin()) {
				customerJson.put("customerOriginName", bcvMap.get(Long.parseLong(customer.getCustomerOrigin())));
			}
		}
		return customerJson;
	}

	// 查看
	@RequestMapping(value = "view", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes view(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:payDeposit:view"))) {
			try {
				Response<PayDeposit> response = payDepositServiceFacade.findById(id);
				if (response.isSuccess()) {
					ar.setSucceed(response.getEntity());
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}

	// 修改
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes edit(PayDepositDto dto) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用修改接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:payDeposit:edit"))) {
			try {
				Response<Integer> response = payDepositServiceFacade.updateByPrimaryKey(dto, true);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				} else {
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
		}
		return ar;
	}

	// 删除
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes delete(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:payDeposit:delete"))) {
			try {
				Response<Integer> response = payDepositServiceFacade.deleteByPrimaryKey(id);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				} else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
		}
		return ar;
	}

	// 分页查询
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public Page<PayDepositDto> list(PayDepositDto dto, Integer limit, Integer page) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:payDeposit:list")) {
			try {
				if (dto.getCheckDateAfter() != null && !dto.getCheckDateAfter().equals("")) {
					dto.setCheckDateAfter(dto.getCheckDateAfter() + " 23:59:59");
				}
				if (dto.getEndTimeAfter() != null && !dto.getEndTimeAfter().equals("")) {
					dto.setEndTimeAfter(dto.getEndTimeAfter() + " 23:59:59");
				}
				if (dto.getDidTimeAfter() != null && !dto.getDidTimeAfter().equals("")) {
					dto.setDidTimeAfter(dto.getDidTimeAfter() + " 23:59:59");
				}
				//录入时间
				if (dto.getCreateTimeBefore1() != null && !dto.getCreateTimeBefore1().equals("")) {
					dto.setCreateTimeBefore1(dto.getCreateTimeBefore1() + " 00:00:00");
				}
				if (dto.getCreateTimeAfter1() != null && !dto.getCreateTimeAfter1().equals("")) {
					dto.setCreateTimeAfter1(dto.getCreateTimeAfter1() + " 23:59:59");
				}
				dto.setOrders(" t.create_time desc ");
				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				dto.setPermissionUserId(user.getId());

				// 项目数据权限资源缓存
				String resourcesCode = ShiroUtil.getDataPermissionResources(dto.getResourcesName());
				if (null == dto.getResourcesCode() || "".equals(dto.getResourcesCode())) {
					dto.setResourcesCode(resourcesCode);
				} else if ("".equals(resourcesCode)) {
					ShiroUtil.setDataPermissionResources(dto.getResourcesName(), dto.getResourcesCode());
				}

				Response<Page<PayDepositDto>> depositListResDto = payDepositService.getPayDepositList(dto, limit, page);
				if (depositListResDto.isSuccess()) {
					Page<PayDepositDto> pages = depositListResDto.getEntity();
					pages.setPageNumber(page);
					return pages;
				} else {
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
		return new Page<PayDepositDto>();
	}

	// marketing:payDeposit:retreat
	@RequestMapping(value = "toRetreat")
	public String toRetreat(String payDepositId, ModelMap map) {
		map.put("payDepositId", payDepositId);
		return "/customer/payDeposit/retreat";
	}

	// marketing:payDeposit:retreatView
	@RequestMapping(value = "toRetreatView")
	public String toRetreatView(String id, ModelMap map, String processFlag) {
		Response<BusinessAbnorma> businessAbnormaResponse = businessAbnormaServiceFacade.findById(Long.valueOf(id));
		map.put("payDepositId", businessAbnormaResponse.getEntity().getBusinessId());
		map.put("businessAbnormaId", id);
		map.put("tId", id);
		map.put("processFlag", processFlag);
		map.put("auditStatus", businessAbnormaResponse.getEntity().getAuditStatus());
		map.put("procInstId", businessAbnormaResponse.getEntity().getProcInstId());
		return "/customer/payDeposit/retreatView";
	}

	// marketing:payDeposit:retreat
	@RequestMapping(value = "submitRetreat")
	public @ResponseBody
	AjaxRes submitRetreat(Long payDepositId, String remark,String fileUrlArr, String imageType) {
		AjaxRes ar = getAjaxRes();
		try {
			User user = ShiroUtil.getCurrentUser();
			Response<PayDeposit> payDepositResponse = payDepositServiceFacade.findById(payDepositId);
			if (!payDepositResponse.isSuccess() || null == payDepositResponse.getEntity()) {
				ar.setFailMsg(Const.SAVE_FAIL);
				return ar;
			}
			Long projectId = payDepositResponse.getEntity().getProjectId();
			if (null == projectId) {
				ar.setFailMsg("项目不存在!");
				return ar;
			}

			// 动态获取价格方案流程KEY
			/*String startProcessKey = activitiProcessService.getProcessKey(user.getMerchantId(), projectId,
					ProcessTypeEnums.PROCESS_KEY_4);
			if (StringUtils.isEmpty(startProcessKey)) {
				ar.setFailMsg("项目未设置价格方案流程,请去项目流程菜单配置！");
				return ar;
			}
			// 检查流程节点是否已设置人员
			String processKey = startProcessKey;
			boolean isSeting = activitiProcessService.checkNodeUser(user.getMerchantId(), projectId, processKey);
			if (!isSeting) {
				ar.setFailMsg("退认筹审批流程节点人员未设置");
				return ar;
			}*/
			BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
			businessAbnormaDto.setMerchantId(user.getMerchantId());
			businessAbnormaDto.setBusinessId(Long.valueOf(payDepositId));
			businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_7.getNo());
			ResponseList<BusinessAbnorma> responseList = businessAbnormaServiceFacade.findByDto(businessAbnormaDto);
			if (responseList.isSuccess() && null != responseList.getEntity()) {
				for (BusinessAbnorma ab : responseList.getEntity()) {
					if (ab.getAuditStatus().equals(AuditStatusEnum.AUDIT.getNo())
							|| ab.getAuditStatus().equals(AuditStatusEnum.TOSUBMIT.getNo())) {
						ar.setFailMsg("存在审批中的退认筹记录，不能重复提交！");
						return ar;
					}
				}
			}
			PayDeposit payDeposit = payDepositResponse.getEntity();
			
			BusinessAbnormaDto dto = new BusinessAbnormaDto();
			dto.setBusinessId(payDepositId);
			dto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_7.getNo());
//			dto.setAuditStatus(AuditStatusEnum.TOSUBMIT.getNo());

			dto.setAuditStatus(AuditStatusEnum.REJECT.getNo());
			dto.setRemark(remark);
			dto.setMerchantId(user.getMerchantId());
			dto.setCreateUserId(user.getId());
			dto.setDelFlag("0");
			dto.setUpdateUserId(user.getId());
			dto.setUpdateTime(new Date());
			dto.setUserCode(user.getUserCode());
			dto.setAccessCode(payDeposit.getAccessCode());
			Response<BusinessAbnormaDto> response = businessAbnormaServiceFacade.save(dto);
			if (response.isSuccess()) {
				// 启动流程
				// 判断是否为无房认筹 如果是则取客户对应的项目负责人
				Map<String, Object> variables = new HashMap<String, Object>();

//				identityService.setAuthenticatedUserId(user.getUserAccount());
//				String pid = activitiProcessService.startProcessInstance(user.getMerchantId(), projectId, processKey,
//						response.getEntity().getId().toString(), variables);
				// 更新审批状态
				BusinessAbnormaDto updateDto = new BusinessAbnormaDto();
				updateDto.setId(response.getEntity().getId());
//				updateDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
				updateDto.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
				updateDto.setProcInstId("sys_auto");
				updateDto.setCheckDate(new Date());
				businessAbnormaServiceFacade.updateByPrimaryKey(updateDto, true);
				ar.setSucceed(response.getEntity().getId());

				//保存流程附件
				if(StringUtils.isNotBlank(fileUrlArr)){
                 	wsImageService.uploadAttachment(fileUrlArr, String.valueOf(response.getEntity().getId()), imageType, response.getEntity().getAccessCode());
                }
				
				// 创建并发送提醒消息
				/*
				 * CommonResDTO resDto = payDepositServiceFacade.addNotice_TRC(response.getEntity(), variables, pid); if
				 * ("1".equals(resDto.getResult())) { logger.error("创建并发送消息: ", "消息创建并发送成功!"); }
				 */

				//更新认筹表状态
				PayDepositDto payDepositDto = new PayDepositDto();
				BeanUtils.copyProperties(payDepositResponse.getEntity(),payDepositDto);
				payDepositDto.setAuditStatus("3");
				payDepositDto.setBusinessStatus("5");
				payDepositServiceFacade.updateByPrimaryKey(payDepositDto,true);


                //记录应退款记录
                NeedReceiveRefundDto needReceiveRefundDto=new NeedReceiveRefundDto();
                needReceiveRefundDto.setRelationId(payDeposit.getId());
                needReceiveRefundDto.setBusinessType("0");
                needReceiveRefundDto.setTotalReceivablesAmount(payDeposit.getPayDepositAmount());
                needReceiveRefundDto.setCustomerId(payDeposit.getCustomerId());
                needReceiveRefundDto.setRoomId(payDeposit.getRoomId());
                needReceiveRefundDto.setStatus("1");
                needReceiveRefundDto.setPostponedStatus("0");
                needReceiveRefundDto.setDocType("1");
                needReceiveRefundDto.setRemark("退筹款");
                needReceiveRefundDto.setHousingFundType(HousingFundTypeEnum.FUNDTYPE_2.getNo());
                needReceiveRefundDto.setBusinessFlag(BusinessFlagEnum.BUSINESSFLAG_4.getNo());
                needReceiveRefundDto.setPostponedStatus("0");

                needReceiveRefundDto.setMerchantId(payDeposit.getMerchantId());
                needReceiveRefundDto.setUserCode(payDeposit.getUserCode());
                needReceiveRefundDto.setAccessCode(payDeposit.getAccessCode());
                needReceiveRefundDto.setCreateUserId(payDeposit.getCreateUserId());
                needReceiveRefundDto.setDelFlag("0");
                needReceiveRefundDto.setUpdateUserId(payDeposit.getUpdateUserId());
                needReceiveRefundDto.setUpdateTime(new Date());
                Response<NeedReceiveRefundDto> nrrdSaveResponse=needReceiveRefundServiceFacade.save(needReceiveRefundDto);
                if(!nrrdSaveResponse.isSuccess()){
                    throw new Exception(nrrdSaveResponse.getResultMessage());
                }

                /**
                 * 查询客户业务状态，并同步更新客户状态
                 */
                String busStatus = customerServiceFacade.queryCustomerBusiness(payDeposit.getCustomerId());
                CustomerDto cusDto = new CustomerDto();
                cusDto.setId(payDeposit.getCustomerId());
                if(busStatus != null){
                    cusDto.setCustomerStatus(CustomerStatusEnum.getByDescription(busStatus).getNo());
                    Response<Integer> responseCusDto = customerServiceFacade.updateByPrimaryKey(cusDto, true);
                    if(!responseCusDto.isSuccess()){
                        throw new Exception("客户状态更新出错");
                    }
                }else{
                    Response<Customer> customerEntity = customerServiceFacade.findById(payDeposit.getCustomerId());
                    if(customerEntity.getEntity().getCustomerStatusBk() == null){
                        cusDto.setCustomerStatus(CustomerStatusEnum.VISIT.getNo());
                    }else{
                        cusDto.setCustomerStatus(customerEntity.getEntity().getCustomerStatusBk());
                    }
                    Response<Integer> responseCusDto = customerServiceFacade.updateByPrimaryKey(cusDto, true);
                    if(!responseCusDto.isSuccess()){
                        throw new Exception("客户状态更新出错");
                    }
                }
			} else {
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(Const.SAVE_FAIL);
		}

		return ar;
	}

	// marketing:payDeposit:retreatView
	@RequestMapping(value = "loadRetreat")
	public @ResponseBody
	ExtResultVo loadRetreat(Long payDepositId, String businessAbnormaId) {
		ExtResultVo vo = new ExtResultVo();
		vo.setSuccess(true);
		Response<PayDeposit> payDepositResponse = payDepositServiceFacade.findById(payDepositId);
		if (payDepositResponse.isSuccess() && null != payDepositResponse.getEntity()) {
			PayDeposit payDeposit = payDepositResponse.getEntity();
			String payDepositStr = JSON.toJSONString(payDeposit);
			JSONObject data = JSONObject.parseObject(payDepositStr);

			// 客户名称
			Response<Customer> customerResponse = customerServiceFacade.findById(payDeposit.getCustomerId());
			if (customerResponse.isSuccess() && null != customerResponse.getEntity()) {
				data.put("customerName", customerResponse.getEntity().getCustomerName());
			} else {
				data.put("customerName", "");
			}

			// 房号
			Response<ProjectRoom> projectRoomResponse = projectRoomServiceFacade.findById(payDeposit.getRoomId());
			if (projectRoomResponse.isSuccess() && null != projectRoomResponse.getEntity()) {
				data.put("roomName", projectRoomResponse.getEntity().getCombinedName());
			} else {
				data.put("roomName", "");
			}
			Response<User> userResponse = userServiceFacade.findById(payDeposit.getAgentId());
			if (userResponse.isSuccess() && null != userResponse.getEntity()) {
				data.put("agentName", userResponse.getEntity().getUserName());
			} else {
				data.put("agentName", "");
			}
			BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
			businessAbnormaDto.setBusinessId(payDeposit.getId());
			businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_7.getNo());
			businessAbnormaDto.setOrders(" t.create_time DESC");
			ResponseList<BusinessAbnorma> businessAbnormaResponse = businessAbnormaServiceFacade
					.findByDto(businessAbnormaDto);
			data.put("remark", "");
			data.put("tcCreateTime", "");
			if (businessAbnormaResponse.isSuccess() && null != businessAbnormaResponse.getEntity()
					&& businessAbnormaResponse.getEntity().size() > 0) {
				for (BusinessAbnorma ab : businessAbnormaResponse.getEntity()) {
					if (ab.getAuditStatus().equals(AuditStatusEnum.AUDIT.getNo())
							|| ab.getAuditStatus().equals(AuditStatusEnum.TOSUBMIT.getNo())) {
						data.put("remark", ab.getRemark());
						data.put("tcCreateTime", DateUtils.formatDate(ab.getCreateTime(), null));
						break;
					}
				}
			}
			// 退筹原因
			vo.setData(data.toJSONString());
		}

		return vo;
	}

	/**
	 * 客户信息 功能描述: <br>
	 * 〈功能详细描述〉
	 * 
	 * @param payDepositId
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping(value = "selectPayDepositCustomer", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes selectPayDepositCustomer(Long payDepositId) {
		AjaxRes ar = getAjaxRes();
		try {
			Response<PayDepositDto> response = payDepositService.selectPayDepositCustomer(payDepositId);
			if (response.isSuccess() && response.getEntity() != null) {
				ar.setSucceed(response.getEntity());
			} else {
				ar.setRes(Const.FAIL);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setRes(10000);
			ar.setFailMsg(Const.DATA_FAIL);
		}
		return ar;
	}
	
	@RequestMapping(value = "toEdit")
	public String toEdit(ModelMap map, String id, HttpServletRequest request) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:payDeposit:add")) {
			Response<PayDeposit> resPd = payDepositServiceFacade.findById(Long.valueOf(id));
			String customerId = String.valueOf(resPd.getEntity().getCustomerId());
			String roomId = String.valueOf(resPd.getEntity().getRoomId());
			
			Boolean showChooseCustomer = Boolean.FALSE;
			map.put("showChooseCustomer", showChooseCustomer);
			map.put("permitBtn", getPermissionBtnArray());
			User user = ShiroUtil.getCurrentUser();
			String typeName = BaseCodeTypeEnum.getByNo(BaseCodeTypeEnum.TYPE_TWELVE.getNo()).getDes();
			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setMerchantId(user.getMerchantId());
			bcvDto.setTypeName(typeName);
			bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			// *1解决数字排序问题.例如 1,2,10.排序后会显示成 1,10,2
			bcvDto.setOrders("t.sort*1");
			ResponseList<BaseCodeValueDto> resList = baseCodeValueServiceFacade.findListByTypeName(bcvDto);
			List<BaseCodeValueDto> bcvList = resList.getEntity();
			JSONArray dtArray = JSONArray.parseArray(baseCodeValueServiceFacade.getBcvJsonArray(bcvDto));
			map.put("documentType", dtArray.toJSONString());
			map.put("customerId", StringUtils.isBlank(customerId) ? "" : customerId);
			if (StringUtils.isNotBlank(customerId)) {
				Response<Customer> customerResponse = customerServiceFacade.findById(Long.valueOf(customerId));
				if (customerResponse.isSuccess() && null != customerResponse.getEntity()) {
					map.put("customerProjectId", customerResponse.getEntity().getProjectId());
				}
			}

			map.put("roomId", StringUtils.isBlank(roomId) ? "" : roomId);
			map.put("menu", request.getParameter("menu"));
			map.put("payDeposit", resPd.getEntity());
			return "/customer/payDeposit/edit";
		} else {
			return Const.NO_AUTHORIZED_URL;
		}

		/*
		 * if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) { } return Const.NO_AUTHORIZED_URL;
		 */
	}

}
